 app.controller('knowledgebaseCtrl', ["$rootScope","$scope", "$state", "$timeout", "$interval", "SweetAlert", "$modal", "FileUploader", "i18nService", "uiGridConstants", "uiGridGroupingConstants", "Restangular","api_user_data","api_solution", function ($rootScope, $scope, $state, $timeout, $interval, SweetAlert, $modal, FileUploader, i18nService, uiGridConstants, uiGridGroupingConstants, Restangular, api_user_data, api_solution) {
  $scope.langs=i18nService.getAllLangs();
  $scope.lang = 'zh-cn';
  var loginUser = $rootScope.user;
 console.log(' loginUser='+JSON.stringify( loginUser));
  
  $scope.gridOptions = {};
  $scope.gridOptions.data = 'myData';
  $scope.gridOptions.enableColumnResizing = true;
  $scope.gridOptions.enableFiltering = false;
  $scope.gridOptions.enableGridMenu = false;
  $scope.gridOptions.enableRowSelection = true;
  $scope.gridOptions.showGridFooter = true;
  $scope.gridOptions.showColumnFooter = false;
  $scope.gridOptions.fastWatch = true;
  $scope.gridOptions.useExternalPagination = true;
  $scope.gridOptions.paginationPageSizes = [10];
  $scope.gridOptions.paginationPageSize = 10;
  $scope.gridOptions.multiSelect = true;


  $scope.filterUserData = function(key){
    var data ={"idx":"0","sum":"5","user":{"roledata":{"rolecode":"user"}}};
    if(key){
        data['user']={
            'name':key
        };
    }
    api_user_data.fetchDataList('user',data).then(function(response){
        if(response){
            if(response.status=200){
                $scope.approvalusers = response.list;
            }
        }
    })                    
  };

  $scope.addApprovalUser = function(item, model){
    var existUser = false;
    angular.forEach($scope.userdata,function(user){
      if(user.userid==item.id) existUser = true;
    });
    if(existUser){

    }else{
      $scope.userdata.push({userid:item.id,username:item.name});
    }
  }

  $scope.refreshListData = function(style,filterData){
    $scope.ldloading[style.replace('-', '_')] = true;
    if(angular.isUndefined(filterData)){
      filterData = defaultFilterData;
    }
    if(angular.isDefined($scope.searchTypes)){
      filterData['searchType'] = $scope.searchTypes;
    }
    $scope.myData = [];
    console.log("filterData="+filterData)
     
  }

  $scope.classifyClick = function(event, item){
    console.log(event);
    console.log(item);
  }

  var apple_selected, tree, treedata_avm, treedata_geography;
  //$scope.selectedTreeNode = {};ssss
  var i=0;
  $scope.out=[];
  $scope.outdata=[];
  var systemtype=[];
  $scope.my_tree_handler = function (branch) {
      filterData.treeIds = branch.id;
      $scope.selectedTreeNode = branch;
      $scope.output = branch ;
       
      var eqflag = false;
      angular.forEach($scope.outdata,function(item){
        if(item.id==$scope.output.id) eqflag = true;
      });
      if(eqflag){

      }else{
        $scope.outdata.push({
                'name':  $scope.output.label,
                'id' : $scope.output.id
        });
        var postData = {
          typeList:[]
        };
        if($scope.outdata.length>0){
          angular.forEach($scope.outdata, function(data){
            postData.typeList.push({id:data.id});
          })
        }
        
        api_solution.findSolutionTypesUser(postData).then(function(response){
          //Restangular.
           $scope.userdata = response.data;
        });
      }
  };
  
  
  $scope.remove = function(element){
        var removeEl = -1;
        angular.forEach($scope.outdata,function(item, index){
          if(element.id==item.id) removeEl = index;
        });
        if(removeEl!=-1){
            $scope.outdata.splice(removeEl, 1);
            var postData = {
              typeList:[]
            };
            if($scope.outdata.length>0){
              angular.forEach($scope.outdata, function(data){
                postData.typeList.push({id:data.id});
              })
            }
            api_solution.findSolutionTypesUser(postData).then(function(response){
              //Restangular.
               $scope.userdata = response.data;
            });
        }
        
  }

  $scope.removeUser = function(element){
        var removeEl = -1;
        angular.forEach($scope.userdata,function(item, index){
          if(element.userid==item.userid) removeEl = index;
        });
        if(removeEl!=-1){
          $scope.userdata.splice(removeEl, 1);
        }
  }



  function convertListToTree(data, treeMap){
        var idToNodeMap = {}; //Keeps track of nodes using id as key, for fast lookup
        var root = null; //Initially set our loop to null
        var parentNode = null;
        //loop over data
        for(var i = 0; i < data.length; i++) {
            var datum = data[i];
            //each node will have children, so let's give it a "children" poperty
            datum.children = [];

            //add an entry for this node to the map so that any future children can
            //lookup the parent
            idToNodeMap[datum.id] = datum;

            //Does this node have a parent?
            if(typeof datum.parent === "undefined" || datum.parent == null) {
                //Doesn't look like it, so this node is the root of the tree
                root = datum;
                treeMap[datum.id] = root;
            } else {        
                //This node has a parent, so let's look it up using the id
                parentNode = idToNodeMap[datum.parent];

                //We don't need this property, so let's delete it.
                delete datum.parent;

                //Let's add the current node as a child of the parent node.
                parentNode.children.push(datum);        
            }
        }
        return root;
  }

  function convertParentToChildList(data){
      var treeMap = {};
      var list=[];
      convertListToTree(data, treeMap);
      angular.forEach(treeMap,function(item){
          list.push(item);
      });
      return list;
  }
 
 
  $scope.try_async_load = function () {
    $scope.my_data = [];
    $scope.doing_async = true;

    api_solution.findSolutionTypeActions(loginUser.id).then(function(response){
      var data = response.data;
      console.log('data='+JSON.stringify(data));
        var objects = [];

        for (var i = 0; i < data.length; i++) {
            var object = {};
            object.id = data[i][0];
            if(data[i][1] != 0){
               object.parent = data[i][1];
            }
            // if (object.parent == 0) {
            //     object.parent = "#";
            // }
            object.label = data[i][2];
            object.actions = data[i][3]; //权限部分
            object.group = "1";
            object.user = "2";
            object.state = {
                "opened": true
            };
            object.typeName = "type";
            // if()
            if (object.actions.indexOf("2") >= 0) { //知识库类型 具有增加权限--系统管理员
                $scope.showAddSolutionType = true;
            }
            if (object.actions.indexOf("5") >= 0) { //知识库类型 具有授权权限--系统管理员
                $scope.showReviewKnowledgeType = true;
            }
            objects.push(object);
        }
        $scope.my_data = convertParentToChildList(objects);
        $scope.tree_data = angular.copy($scope.my_data);
        if($scope.my_data.length>0){
          $scope.doing_async = false;
        }
    });
  };

  $scope.cancel = function() {
      $scope.userdata=[];
      $scope.outdata=[];               
  };

  $scope.reset = function() {
      $scope.userdata=[];
      $scope.outdata=[];               
  };
  $scope.ok = function() {
    if($scope.outdata.length>0){
      var postData = {
        userList:[],
        typeList:[]
      };
      angular.forEach($scope.outdata, function(data){
          postData.typeList.push({id:data.id});
      });
      angular.forEach($scope.userdata, function(data){
          postData.userList.push({id:data.userid});
      });
      api_solution.addTypeUserAll(postData).then(function(response){
          if(response){
            if(response.status==200){
              $scope.userdata=[];
              $scope.outdata=[];  
              SweetAlert.swal({
                title:"保存成功!",
                type:"success"
              })
            }else{
              SweetAlert.swal({
                title:"保存失败!",
                type:"error"
              })
            }
          }
      });
    }else{
      SweetAlert.swal({
                title:"请选择分类!",
                type:"error"
              })
    }                     
  };

  $scope.try_async_load();

  // $scope.ldloading={};
  
  var filterData = {
    key:'null', 
    status:0, 
    pageIndex:0, 
    pageSum:10, 
    //treeIds:'[]', 
    userId:loginUser.id
  }
 

}]);

 

   

   



 

   

  

   


   

 

